//
//  KKAudioRecorder.m
//  AudioTest
//
//  Created by 康凯 on 2016/12/8.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKAudioRecorder.h"

@interface KKAudioRecorder()<AVAudioRecorderDelegate,AVAudioPlayerDelegate>
@property(strong, nonatomic)NSDictionary *recordSetting;
@property(strong, nonatomic)AVAudioSession *audioSession;
@property(strong, nonatomic)AVAudioRecorder *recorder;
@property(strong, nonatomic)NSURL *url;
@property(strong, nonatomic)AVAudioPlayer *avPlayer;

@end

@implementation KKAudioRecorder

-(instancetype)init{
    if(self=[super init]){
        /*60s:
         kAudioFormatMPEG4AAC, 8000 ~= 124K
         kAudioFormatMPEG4AAC, 16000 ~= 185K
         kAudioFormatAppleIMA4, 8000 ~= 252K
         */
        self.recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
                        [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                        //录音格式,kAudioFormatAppleIMA4大概是kAudioFormatMPEG4AAC的两倍大小.kAudioFormatLinearPCM是无损格式
                         [NSNumber numberWithFloat:16000.0f], AVSampleRateKey,
                        //录音采样率(Hz) 如：AVSampleRateKey==8000/16000/44100/96000（影响音频的质量）
                         [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                        //线性采样位数8,16,24,32,默认 16
                         [NSNumber numberWithInt:1], AVNumberOfChannelsKey,
                        //通道的数目,1 or 2.
                         [NSNumber numberWithInt:AVAudioQualityHigh], AVEncoderAudioQualityKey,
                        //录音的质量
                        //[NSNumber numberWithBool:NO], AVLinearPCMIsBigEndianKey,//大端还是小端 是内存的组织方式
                        //[NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey,//采样信号是整数还是浮点数
                         nil];
        
    }
    return self;
}

-(void)openRecorder{
    self.audioSession=[AVAudioSession sharedInstance];
    NSError *error;
    [self.audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    if(error){
        NSLog(@"error--->%@",error);
    }
    
    NSString *strUrl = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@.aac", strUrl,[self getCurrentTimeLong]]];
    KKLog(@"url---%@",url);
    self.url=url;
    NSError *error1;
    [self.audioSession setActive:YES error:&error1];
    //初始化
    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:self.recordSetting error:&error1];
    self.recorder.delegate=self;
    //开启音量检测
    self.recorder.meteringEnabled = YES;
    [self.recorder recordForDuration:(NSTimeInterval)60];
    if([self.recorder prepareToRecord]){
        [self.recorder record];
    }
    
}

-(void)stopRecorder:(BOOL)shortTime{
    self.shortTime=shortTime;
    [self.recorder stop];
}

- (NSString *)getCurrentTimeLong
{
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    //为字符型
    NSString *timeString = [NSString stringWithFormat:@"%f", a];
    return [timeString substringToIndex:13];
}

- (void)playAudio:(NSString *)url{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    [session setActive:YES error:nil];
    
    KKLog(@"playurl0--->%@",url);
    NSError *error3;
//    self.avPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:url] error:&error3];
    self.avPlayer = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]] error:&error3];
    
    
    if(error3){
        KKLog(@"play error--->%@",error3);
        return;
    }
    self.avPlayer.numberOfLoops = 0;
    self.avPlayer.volume = 1.0f;
    self.avPlayer.delegate=self;
    if([self.avPlayer prepareToPlay]){
        [self.avPlayer play];
        NSLog(@"duration:%f",self.avPlayer.duration);
    }
}

#pragma mark 代理--audioRecorder
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    if(!self.shortTime){
        self.recorderSuccessBlock(recorder.url);
    }
}
#pragma mark 代理--audioPlay
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    KKLog(@"%@",flag?@"yes":@"no");
}
-(void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error{
    KKLog(@"play_error--->%@",error);
}

@end
